<template>
  <a-modal
    v-model="visible"
    :title="titleMap[type]"
    :width="800"
    destroyOnClose
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    centered
    @ok="submit"
    :afterClose="afterClose"
  >
    <a-form-model ref="form" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
      <a-form-model-item label="绑定打印机">
        <a-select
          :value="form.printerNo"
          option-label-prop="label"
          placeholder="请选择打印机"
          @change="handleChangePrinter"
        >
          <a-select-option
            v-for="item in deviceList"
            :value="item.printerNo"
            :key="item.printerNo"
            :label="
              `${item.printerNo}（${
                Dict.getDictItem(Dict.getLocal('terimalStatusDict'), item.terimalStatus).dictLabel
              }）`
            "
          >
            <!-- :disabled="item.bindStatus === 1" -->
            <div class="disFlxJS">
              <span class="disFlxAC">
                {{ item.printerNo }}（{{
                  Dict.getDictItem(Dict.getLocal('terimalStatusDict'), item.terimalStatus).dictLabel
                }}）
                <DictTag :options="Dict.getLocal('printBindStatusDict')" :value="item.bindStatus" isBadge />
                <div v-if="item.activityName" class="ellipsis-text">（{{ item.activityName }}）</div>
              </span>
              <span class="disFlx">
                <a v-if="item.bindStatus === 1" class="_ml-5" @click="handleUnbinding(item)"> 解绑 </a>
                <a v-else class="_ml-5" style="color: #52c41a"> 可选 </a>
              </span>
            </div>
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="打印机名称" prop="signName">
        <a-input v-model="form.signName" :disabled="type === 'bind'" placeholder="请输入打印机名称" allowClear />
      </a-form-model-item>
      <a-form-model-item label="关联组织" prop="assocTenantId">
        <a-select v-model="form.assocTenantId" placeholder="请选择关联组织" @change="handleChangeOrganization">
          <a-select-option v-for="item in organizationList" :key="item.tenantId" :value="item.tenantId">{{
            item.orgName
          }}</a-select-option>
        </a-select>
      </a-form-model-item>

      <a-form-model-item label="选择胸卡模板">
        <a-radio-group v-model="form.printStyle">
          <a-radio v-for="(item, index) in PrintStyleDefDict" :key="item.dictValue" :value="item.dictValue">
            <span>{{ item.dictLabel }}</span>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="样式预览">
        <div class="disFlxAC">
          <img :src="Dict.getDictItem(PrintStyleDefDict, form.printStyle).image" style="width: 160px;height:auto;" />
          <div class="_ml-10">
            <div>打印内容：（可从活动信息收集表选择打印）</div>
            <div>
              <span>自定义字段1：</span>
              <a-select
                v-model="form.itemId1"
                option-label-prop="label"
                placeholder="请选择打印字段"
                style="width: 200px"
              >
                <a-select-option
                  v-for="item in customFields"
                  :value="item.id"
                  :key="item.id"
                  :label="item.showName"
                  :disabled="item.id === form.itemId2 || !enableFieldTypes.includes(item.itemType)"
                >
                  {{ item.showName }}
                </a-select-option>
              </a-select>
            </div>
            <div>
              <span>自定义字段2：</span>
              <a-select
                v-model="form.itemId2"
                option-label-prop="label"
                placeholder="请选择打印字段"
                style="width: 200px"
              >
                <a-select-option
                  v-for="item in customFields"
                  :value="item.id"
                  :key="item.id"
                  :label="item.showName"
                  :disabled="item.id === form.itemId1 || !enableFieldTypes.includes(item.itemType)"
                >
                  {{ item.showName }}
                </a-select-option>
              </a-select>
            </div>
          </div>
        </div>
        <a-button class="_mt-10" type="primary" @click="handlePrint">试打印胸卡</a-button>
        <div class="disFlxAC fz-14 _mt-12" style="line-height: 22px;">
          <a-icon type="question-circle" style="color:#C9CDD4;" theme="filled" />
          <span style="color: #86909C;" class="_ml-4">猜你想问：</span>
          <a
            href="https://www.yuque.com/hbkj2024/mdvank/oxg7lo9vqqgd9mgm?singleDoc"
            target="_blank"
            style="text-decoration: underline;color: #165DFF;"
          >
            怎么调试打印机
          </a>
        </div>
      </a-form-model-item>
      <a-form-model-item label="备注">
        <a-textarea v-model="form.remark" placeholder="请输入备注" :rows="4" allowClear />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { activityDeviceList, devicePrint, getActivityOrganization } from '@/api/activity/activity'
import { actconfigAdd, actconfigUpdate, deviceBind } from '@/api/activity/sign'
import { activityFormItemList } from '@/api/activity/register'
import DictTag from '@/components/DictTag'
import { isNumber } from 'lodash-es'

export default {
  components: {
    DictTag
  },
  props: {
    // 活动主办方-组织ID
    defaultOrganization: {
      type: Number
    }
  },
  computed: {
    PrintStyleDefDict() {
      return this.Dict.getLocal('PrintStyleDefDict')
    }
  },
  data() {
    return {
      visible: false,
      form: {
        id: undefined,
        signName: undefined,
        assocTenantId: undefined, // 合作协会组织
        assocTenantName: undefined, // 合作协会组织
        printerNo: undefined,
        printStyle: 2,
        remark: '',
        itemId1: -2,
        itemId2: -3
      },
      rules: {
        signName: [{ required: true, message: '请输入签到码名称', trigger: 'blur' }],
        assocTenantId: [{ required: true, message: '请选择关联组织', trigger: 'change' }]
      },
      confirmLoading: false,
      type: 'add',
      titleMap: {
        add: '新增',
        edit: '编辑',
        bind: '绑定打印机'
      },
      rowData: {},
      deviceList: [],
      customFields: [],
      organizationList: [],
      enableFieldTypes: [
        'Input',
        'InputNumber',
        'Select',
        'RadioGroup',
        'DatePicker',
        'TimePicker',
        'AreaPicker',
        'InputPhone',
        'YearPicker',
        'MonthPicker',
        'InputSearch'
      ]
    }
  },
  methods: {
    handleChangePrinter(val) {
      if (!this.form.signName || this.form.signName == this.form.printerNo) {
        this.form.signName = val
      }
      this.form.printerNo = val
    },
    openModel(data) {
      this.rowData = data.row
      this.type = data.type
      this.visible = true
      this.getActivityDeviceList()
      this.$nextTick(() => {
        if (this.type === 'add') {
          Object.assign(this.$data.form, this.$options.data().form)
        } else {
          Object.keys(this.form).forEach(k => {
            if (k === 'printStyle') {
              this.form[k] = isNumber(this.rowData[k]) ? this.rowData[k] : 2
            } else {
              this.form[k] = this.rowData[k]
            }
          })
          this.form.itemId1 = (this.rowData.itemId1 && Number(this.rowData.itemId1)) || -2
          this.form.itemId2 = (this.rowData.itemId2 && Number(this.rowData.itemId2)) || -3
        }
        this.form.activityId = this.$route.query.activityId
        this.form.activityName = data.activityName
        if (!this.form.assocTenantId && this.defaultOrganization) {
          // 未选择关联组织时默认选择主办方
          this.form.assocTenantId = this.defaultOrganization
        }
        this.getActivityFormItemList()
        this.getOrganizationList()
      })
    },
    closeModel() {
      this.visible = false
    },
    afterClose() {
      this.form.id = undefined
      this.$refs.form.resetFields()
    },
    async getActivityDeviceList() {
      let { data } = await activityDeviceList()
      this.deviceList = data.records || []
    },
    getOrganizationList() {
      getActivityOrganization(this.form.activityId).then(res => {
        this.organizationList = res.data

        if (this.form.assocTenantId && !this.form.assocTenantName) {
          this.handleChangeOrganization(this.form.assocTenantId)
        }
      })
    },
    handleChangeOrganization(e) {
      const item = this.organizationList.find(v => v.tenantId === e)
      if (item) {
        this.form.assocTenantName = item.orgName
      }
    },
    async getActivityFormItemList() {
      let res = await activityFormItemList(this.form.activityId)
      this.customFields = (res.data || []).filter(f => this.enableFieldTypes.includes(f.itemType))
      let index1 = this.customFields.findIndex(f => f.id === this.form.itemId1)
      if (index1 === -1) this.form.itemId1 = undefined

      let index2 = this.customFields.findIndex(f => f.id === this.form.itemId2)
      if (index2 === -1) this.form.itemId2 = undefined
    },
    handleUnbinding(row) {
      var _this = this
      this.$confirm({
        title: '解绑?',
        content: '是否确定解绑该打印机?',
        onOk: async () => {
          await deviceBind({
            id: row.actBindId,
            printerNo: row.printerNo,
            printStyle: 2,
            activityId: row.activityId,
            activityName: row.activityName,
            bindStatus: 0
          })
          _this.$message.success(`解绑成功`)
          if (_this.form.printerNo === row.printerNo) {
            _this.form.printerNo = undefined
            _this.form.printStyle = 2
          }
          _this.getActivityDeviceList()
          _this.$emit('success')
        },
        onCancel() {}
      })
    },
    //试打印胸卡
    async handlePrint() {
      try {
        if (!this.form.printerNo) {
          this.$message.error('请选择试打印的打印机')
          return
        }
        let item1 = this.customFields.find(f => f.id === this.form.itemId1) || {}
        let item2 = this.customFields.find(f => f.id === this.form.itemId2) || {}
        await devicePrint({
          ...this.form,
          activityId: undefined,
          activityTitle: '深圳市XX商会第三届第三次会员大会暨十周年庆典',
          keyStr1: '张某三',
          keyStr2: '常务副会长',
          keyStr3: item1.name || '深圳市XX科技有限公司',
          keyStr4: item2.name || '总经理',
          // keyStr5: this.form.assocTenantName,
          chestItem: [
            {
              itemName: '晚宴安排',
              itemContent: '一排5号桌'
            }
          ]
        })
        this.$message.success('打印成功')
      } catch (error) {
        this.$message.error('打印失败')
      }
    },
    submit() {
      console.log(JSON.parse(JSON.stringify(this.form)))
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.confirmLoading = true
          try {
            this.form.id ? await actconfigUpdate({ ...this.form }) : await actconfigAdd({ ...this.form })
            this.confirmLoading = false
            this.$message.success(`${this.type === 'bind' ? '操作' : this.titleMap[this.type]}成功`)
            this.closeModel()
            this.$emit('success')
          } catch (error) {
            this.confirmLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ellipsis-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
